import { useEffect,useState } from 'react';
import { withRouter } from 'next/router';
import { Row, Col, Affix, Tag, Divider } from 'antd';
import Head from 'next/head';
import marked from 'marked';
import hljs from 'highlight.js';
import 'highlight.js/styles/monokai-sublime.css';
import Tocify from '../components/tocify.tsx';
// import ReactMarkdown from 'react-markdown';
// import MarkNav from 'markdown-navbar';
// import 'markdown-navbar/dist/navbar.css';
import API from '../util/apiUrl';
import iconUrl from '../util/iconUrl';
import Header from '../components/header';
import Footer from '../components/footer';
import cssDetail from '../static/style/pages/detail.scss';
import '../static/style/pages/detail.css';
import { createFromIconfontCN, LikeOutlined } from '@ant-design/icons';

const IconFont = createFromIconfontCN({
  scriptUrl: iconUrl,
});

const Detail = (props) => {
  console.log('detail props', props);
  // const [skillTypeList,setSkillTypeList]=useState([])
  useEffect(() => {
    showTop();

    if (props.data[0]) {
      setData(getRecommendList(props.data[0])) 
    }
    // getSkillType()
  }, []);

  const [data,setData] = useState(props.data[0]) ;
  // 获取压缩图片地址
  const getRecommendList = (data) => {
    // let recommendList = list.map((i) => {
      let ysimg;
      if (data.img) {
        ysimg = data.img.split('.');
        ysimg[ysimg.length - 2] = ysimg[ysimg.length - 2] + 'ys';
        ysimg = ysimg.join('.');
      } else {
        ysimg = null;
      }
      data = {...data,ysimg}
    //   return {
    //     ...i,
    //     ysimg,
    //   };
    // });
    return data
  };

  const tagsColor = ['blue', 'geekblue', 'purple', 'lime', 'green', 'cyan'];

  // markdown
  const tocify = new Tocify();
  const renderer = new marked.Renderer();
  renderer.heading = function (text, level, raw) {
    const anchor = tocify.add(text, level);
    return `<a id="${anchor}" href="#${anchor}" class="anchor-fix"><h${level}>${text}</h${level}></a>\n`;
  };

  marked.setOptions({
    renderer: renderer,
    gfm: true,
    pedantic: false,
    sanitize: false,
    tables: true,
    breaks: false,
    smartLists: true,
    smartypants: false,
    highlight: function (code) {
      return hljs.highlightAuto(code).value;
    },
  });

  let html = marked(data.content);

  // let markdown =
  //   '# P01:课程介绍和环境搭建\n' +
  //   '[ **M** ] arkdown + E [ **ditor** ] = **Mditor**  \n' +
  //   '> Mditor 是一个简洁、易于集成、方便扩展、期望舒服的编写 markdown 的编辑器，仅此而已... \n\n' +
  //   '**这是加粗的文字**\n\n' +
  //   '*这是倾斜的文字*`\n\n' +
  //   '***这是斜体加粗的文字***\n\n' +
  //   '~~这是加删除线的文字~~ \n\n' +
  //   '`console.log(111)` \n\n' +
  //   '# p02:来个Hello World 初始Vue3.0\n' +
  //   '> aaaaaaaaa\n' +
  //   '>> bbbbbbbbb\n' +
  //   '>>> cccccccccc\n' +
  //   '***\n\n\n' +
  //   '# p03:Vue3.0基础知识讲解\n' +
  //   '> aaaaaaaaa\n' +
  //   '>> bbbbbbbbb\n' +
  //   '>>> cccccccccc\n\n' +
  //   '# p04:Vue3.0基础知识讲解\n' +
  //   '> aaaaaaaaa\n' +
  //   '>> bbbbbbbbb\n' +
  //   '>>> cccccccccc\n\n' +
  //   '#5 p05:Vue3.0基础知识讲解\n' +
  //   '> aaaaaaaaa\n' +
  //   '>> bbbbbbbbb\n' +
  //   '>>> cccccccccc\n\n' +
  //   '# p06:Vue3.0基础知识讲解\n' +
  //   '> aaaaaaaaa\n' +
  //   '>> bbbbbbbbb\n' +
  //   '>>> cccccccccc\n\n' +
  //   '# p07:Vue3.0基础知识讲解\n' +
  //   '> aaaaaaaaa\n' +
  //   '>> bbbbbbbbb\n' +
  //   '>>> cccccccccc\n\n' +
  //   '``` var a=11; ```';

  // 直接显示顶部
  const showTop = () => {
    document.body.scrollTop = document.documentElement.scrollTop = 0;
  };
  // 统计字数
  const getHTMLLength = (str) => {
    str = str.replace(/<\/?[^>]*>/g, ''); //去除HTML tag
    str = str.replace(/[ | ]*\n/g, '\n'); //去除行尾空白
    //str = str.replace(/\n[\s| | ]*\r/g,'\n'); //去除多余空行
    str = str.replace(/ /gi, ''); //去掉
    var arrEntities = { lt: '<', gt: '>', nbsp: ' ', amp: '&', quot: '"' };
    return str.replace(/&(lt|gt|nbsp|amp|quot);/gi, function (all, t) {
      return arrEntities[t];
    }).length;
  };
  // 获取句子
  // const getSkillType=()=>{
  //   Api.getSkillType().then(res=>{
  //     console.log('获取到句子',res)
  //     setSkillTypeList()
  //   })
  // }
  return (
    <>
      <Head>
        <title>yzyの博客-文章详情</title>
        <link
          rel="shortcut icon"
          href="../static/img/bitbug_favicon.ico"
          type="image/x-icon"
        />
        {/* <base target="_blank"/> */}
      </Head>
      <Header current="0" />
      <div className={cssDetail.detail}>
        <div
          className={cssDetail.img}
          style={{
            backgroundImage: `url('${
              data.ysimg 
              // || '/static/img/articleBgc/detailMoren.jpg'
            }')`,
          }}
        >
          <div className={cssDetail.title}>{data.title}</div>
        </div>
        <div className={cssDetail.common}>
          <Row className={cssDetail.comm_main} justify="center">
            <Col xs={24} sm={24} md={18} lg={18} xl={18}>
              <div className={cssDetail.content}>
                <div className={cssDetail.top + ' clear'}>
                  <div className={cssDetail.tags}>
                    {data.tags
                      ? data.tags.split(',').map((i, idx) => (
                          <Tag key={idx} color={tagsColor[idx % 6]}>
                            {i}
                          </Tag>
                        ))
                      : ''}
                  </div>
                  <div className={cssDetail.skillType}>
                    <IconFont type="icon-shaixuan" />
                    {
                      data.skillType||'未知'
                    }
                    {/* {data.skillTypeId + '类别'} */}
                  </div>
                </div>
                <div className={cssDetail.msg}>
                  <span>
                    <IconFont type="icon-shijian" />
                    发布日期:&nbsp;
                    {data.updateTime}
                  </span>
                  <span>
                    <IconFont type="icon-shijian" />
                    更新日期:&nbsp;
                    {data.alterTime || '无'}
                  </span>
                  <span>
                    <IconFont type="icon-usercenter" />
                    作者:&nbsp;
                    {data.author || 'yzy'}
                  </span>
                  <span>
                    <IconFont type="icon-shaixuan" />
                    字数:&nbsp;
                    {getHTMLLength(html)}
                  </span>
                  <span>
                    <IconFont type="icon-hot" />
                    浏览人数:&nbsp;
                    {data.people || '未知'}
                  </span>
                </div>
                <Divider style={{ marginTop: 12 }} />
                <div
                  className={cssDetail.article + ' detailed-content'}
                  dangerouslySetInnerHTML={{ __html: html }}
                >
                  {/* <ReactMarkdown source={data.content} escapeHtml={false} /> */}
                </div>
              </div>
            </Col>
            <Col xs={0} sm={0} md={6} lg={6} xl={6}>
              <div className={cssDetail.sidebar}>
                <Affix offsetTop={70}>
                  <div className="detailed-nav comm-box">
                    <div className="nav-title">文章目录</div>
                    <div className="toc-list">{tocify && tocify.render()}</div>
                  </div>
                  {/* <div>
                    <QqOutlined />
                    文章目录
                    <MarkNav
                      className={cssDetail.articleMenu}
                      source={data.content}
                      ordered={false}
                    />
                  </div> */}
                </Affix>
              </div>
            </Col>
          </Row>
        </div>
        <Footer />
      </div>
    </>
  );
};

Detail.getInitialProps = async (props) => {
  let res = await API.getArticleDetails(props.query.id);
  // let skillTypeList = await API.getSkillType();
  // console.log('res000', skillTypeList,);
  return { data: [...res.data] };
};

export default withRouter(Detail);
